/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.starter.iam.authentication.interceptor;

import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.error.CommonErrorCode;
import com.snail.starter.commons.exception.LoginException;
import com.snail.starter.iam.annotation.IgnoreToken;
import com.snail.starter.iam.authentication.interfaces.IAuthentication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zgadmin
 * @date 2025/8/26 14:09
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor, Ordered {

    @Resource
    IAuthentication iAuthentication;

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            if (log.isDebugEnabled()) {
                log.debug("handler not instanceof HandlerMethod request uri:{}", request.getRequestURI());
            }
            return true;
        }
        UserContext userContext = iAuthentication.authentication(request);
        if (isIgnoreToken(request, handler) || !userContext.isDefault()) {
            return true;
        }
        log.error("not login:{}", request.getRequestURI());
        throw LoginException.of(CommonErrorCode.NOT_LOGIN_IN);
    }

    public boolean isIgnoreToken(HttpServletRequest request, Object handler) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (!handlerMethod.getMethod().isAnnotationPresent(IgnoreToken.class)) {
            return false;
        }
        log.debug("ignore token request uri:{}", request.getRequestURI());
        return true;
    }
}